#include "ColladaGLSLShaderData.h"


namespace lib3dw
{
	ColladaGLSLShaderData::ColladaGLSLShaderData(FCDocument* colladaDocument)
	{
		FCDEffectLibrary *library = colladaDocument->GetEffectLibrary();
		ProcessEffectLibrary(library);
	}
	
	ColladaGLSLShaderData::~ColladaGLSLShaderData()
	{
	}
	
	void ColladaGLSLShaderData::ProcessEffectLibrary(FCDEffectLibrary* library)
	{
		for (size_t j = 0; j < library->GetEntityCount(); ++j)
		{
			FCDEffect* effect = library->GetEntity(j);
			FCDEffectProfileFX* profile = (FCDEffectProfileFX*)effect->FindProfile(FUDaeProfileType::GLSL);
			if(profile != NULL)
			{
				FCDEffectTechniqueContainer& glslTechniques = profile->GetTechniqueList();
				FCDEffectTechnique* glslTechnique = glslTechniques.front();
				std::string techniqueName = glslTechnique->GetName();
				FCDEffectPassContainer& apass = glslTechnique->GetPassList();
				size_t passCount = apass.size();
				std::string passName = "";
				const char* vertexShaderFilename = NULL;
				const char* fragmentShaderFilename = NULL;
				
				for (size_t i = 0; i < passCount; ++i)
				{
					FCDEffectPass* pass = apass[i];
					passName = pass->GetPassName();
					FCDEffectPassShader* vertexShader = pass->GetVertexShader();
					FCDEffectPassShader* fragmentShader = pass->GetFragmentShader();
					
					vertexShaderFilename = vertexShader->GetCode() != NULL ? vertexShader->GetCode()->GetFilename().c_str()  : "";
					fragmentShaderFilename = fragmentShader->GetCode() != NULL ? fragmentShader->GetCode()->GetFilename().c_str() : "";
				}
				
				//HACK we only support shader passes that consist of exactly one vertex and exactly one fragment shader
				GLSLShaderProgram* currentProgram = NULL;
				std::map<std::string, GLSLShaderProgram*>* loadedShaderPrograms = GLSLShaderProxySingleton::Instance()->GetLoadedShaderPrograms();
				if(vertexShaderFilename != NULL && fragmentShaderFilename != NULL)
				{
					if((*loadedShaderPrograms)[passName] == NULL)
					{
						currentProgram = new GLSLShaderProgram(passName, vertexShaderFilename, fragmentShaderFilename);
						currentProgram->Link();
						(*loadedShaderPrograms)[passName] = currentProgram;
					}
					shaderPasses.push_back((*loadedShaderPrograms)[passName]->GetId());
				}
			}
		}
	}
}
